package service;

/**
 * Created by fanzhenyu02 on 2020/9/17.
 */

import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.*;
import java.security.cert.Certificate;

public class ExportCer {

    //导出证书 base64格式
    public static void exportCert(KeyStore keyStore, String alias, String exportFile) throws Exception {
        Certificate certificate = keyStore.getCertificate(alias);
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = encoder.encode(certificate.getEncoded());
        try (FileWriter fw = new FileWriter(exportFile)) {
            fw.write("-----BEGIN CERTIFICATE-----\r\n");//非必须
            fw.write(encoded);
            fw.write("\r\n-----END CERTIFICATE-----");//非必须
        }
    }

    //得到KeyPair
    public static KeyPair getKeyPair(KeyStore keyStore, String alias, char[] password) {
        try {
            Key key = keyStore.getKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate certificate = keyStore.getCertificate(alias);
                PublicKey publicKey = certificate.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
            e.printStackTrace();
        }
        return null;
    }

    //导出私钥
    public static void exportPrivateKey(PrivateKey privateKey, String exportFile) throws Exception {
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = encoder.encode(privateKey.getEncoded());
        try (FileWriter fileWriter = new FileWriter(exportFile)) {
            fileWriter.write("-----BEGIN PRIVATE KEY-----\r\n");//非必须
            fileWriter.write(encoded);
            fileWriter.write("\r\n-----END PRIVATE KEY-----");//非必须
        }
    }

    //导出公钥
    public static void exportPublicKey(PublicKey publicKey, String exportFile) throws Exception {
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = encoder.encode(publicKey.getEncoded());
        try (FileWriter fileWriter = new FileWriter(exportFile)) {
            fileWriter.write("-----BEGIN PUBLIC KEY-----\r\n");//非必须
            fileWriter.write(encoded);
            fileWriter.write("\r\n-----END PUBLIC KEY-----");//非必须
        }
    }

    //keytool -genkey -alias "MOBIKE.CERT.KEY" -keystore mobile.keystore -keyalg RSA -validity 3650
    //keytool -genkey -alias "syb.meituan" -storetype PKCS12  -keystore xwbank.pfx -keyalg RSA -validity 36500
    public static void main(String[] args) throws Exception {
        String baseDir = "/Users/vonmax/Downloads/FW__证书更换测试环境验证流程及案例模版/test/";

        String keyStoreType = "PKCS12";
        String keystoreFile = baseDir + "mttestcert.pfx";
        String password = "000000"; //keystore的解析密码
        String friendPassword = "000000";//条目的解析密码

        try (FileInputStream fis = new FileInputStream(keystoreFile)) {
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(fis, password.toCharArray());

            java.util.Enumeration<String> s = keyStore.aliases();
            while (s.hasMoreElements()) {
                System.out.println(s.nextElement());
            }
            String alias = "0c58e0f4e1184cf78427###20200908200258887";//条目别名
            String exportCertFile = baseDir + "mttestcert.cer";
            String exportPrivateFile = baseDir + "mttestcert.privateKey.txt";
            String exportPublicFile = baseDir + "mttestcert.publicKey.txt";

            ExportCer.exportCert(keyStore, alias, exportCertFile);
            KeyPair keyPair = ExportCer.getKeyPair(keyStore, alias, friendPassword.toCharArray()); //注意这里的密码是你的别名对应的密码，不指定的话就是你的keystore的解析密码
            ExportCer.exportPrivateKey(keyPair.getPrivate(), exportPrivateFile);
            ExportCer.exportPublicKey(keyPair.getPublic(), exportPublicFile);

            System.out.println("OK");
        }
    }
}